package com.bbs.controller;


import com.bbs.common.Result;

import com.bbs.pojo.UserInfo;
import com.bbs.properties.MyUserDetails;
import com.bbs.service.IUserInfoService;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-05-03
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserInfoService userInfoService;

    @RequestMapping("/login")
    public String loginPage() {
        log.info("用户登录");
        return "login";
    }

    @RequestMapping("/loginFail")
    public String loginFail() {
        log.info("用户登录失败");
        return "login";
    }
    @GetMapping("/info")
    public String info(Model model, Authentication authentication) {
        // 从 Authentication 中获取 principal
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId(); // 安全获取 id
        UserInfo userInfo = userInfoService.getById(id);
        Result<UserInfo> result = Result.success(userInfo);
        model.addAttribute("result", result);
        return "user-info";
    }
    /**
     * 展示个人信息修改页面
     */
    @GetMapping("/info/edit")
    public String showEditForm(Model model,Authentication authentication ) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId(); // 安全获取 id
        UserInfo userInfo = userInfoService.getById(id);
        Result<UserInfo> result = Result.success(userInfo);
        model.addAttribute("result", result);
        return "updateinfo"; // 对应你的修改页面
    }

    /**
     * 处理个人信息修改提交
     */
    @PostMapping("/update")
    public String updateUserInfo(@ModelAttribute UserInfo userInfo,
                                 Authentication authentication,
                                 RedirectAttributes redirectAttributes) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId();// 安全获取 id
        userInfo.setId(Math.toIntExact(id));
            userInfoService.updateById(userInfo);
                redirectAttributes.addFlashAttribute("success", "个人信息更新成功！");
                return "redirect:/user/info";
    }
}
